import { onMounted, ref } from 'vue'
import { MPaginationOption } from './pagination.model'
import http from '@/utils/request'
import store from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'

export const PaginationHook = (options: MPaginationOption) => {
    const tabelHeight = ref('300px')
    const tableHeaderDom = ref()
    const tableFooterDom = ref()

    const defaultOptions: MPaginationOption = {
        createdIsNeed: true,
        dataListMethod: undefined,
        isPage: true,
        deleteUrl: '',
        primaryKey: 'id',
        exportUrl: '',
        queryForm: {},
        dataList: [],
        current: 1,
        size: 20,
        total: 0,
        pageSizes: [20, 50, 100],
        dataListLoading: false,
        dataListSelections: []
    }

    function mergeDefaultOptions(options: any, props: any): MPaginationOption {
        for (const key in options) {
            if (!Object.getOwnPropertyDescriptor(props, key)) {
                props[key] = options[key]
            }
        }
        return props
    }

    // 覆盖默认值
    // debugger
    const state = mergeDefaultOptions(defaultOptions, options)

    onMounted(() => {
        if (state.createdIsNeed) {
            query()
        }
        tabelHeight.value = store.appStore?.layout.mainBodyHeight + 8 - (tableHeaderDom.value.offsetHeight + tableFooterDom.value.offsetHeight) + 'px'
    })

    async function query() {
        if (!state.dataListMethod) {
            return;
        }
        // debugger
        let paramData = {
            current: state.isPage ? state.current : null,
            size: state.isPage ? state.size : null,
            ...state.queryForm
        };
        if (state.dataListMethod) {
            const { dataList, total } = await state.dataListMethod(paramData);
            state.dataList = dataList
            state.total = state.isPage ? total : 0
        }
    }

    function getDataList() {
        state.current = 1
        query()
    }

    function sizeChangeHandle(val: number) {
        state.current = 1
        state.size = val
        query()
    }

    function currentChangeHandle(val: number) {
        state.current = val
        query()
    }

    // 多选
    function selectionChangeHandle(selections: any[]) {
        state.dataListSelections = selections.map((item: any) => state.primaryKey && item[state.primaryKey])
    }

    // 排序
    function sortChangeHandle(data: any) {
        const { order } = data
        if (order) {
            if (state.queryForm.param)
                state.queryForm.param[data.column.sortable] = order !== 'ascending'
            else
                state.queryForm[data.column.sortable] = order !== 'ascending'

        }
        query()
    }

    function deleteHandle(key: number | string) {
        if (!state.deleteUrl) {
            return
        }
        ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            http.delete(state.deleteUrl + '/' + key).then(() => {
                ElMessage.success('删除成功')
                query()
            })
        }).catch(() => { })
    }

    function deleteBatchHandle(key?: number | string) {
        let data: any
        if (!key) {
            data = state.dataListSelections ? state.dataListSelections : []
            if (data.length === 0) {
                ElMessage.warning('请选择删除记录')
                return
            }
        }
        ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            if (state.deleteUrl) {
                http.get(state.deleteUrl, key ? { params: { id: key } } : { params: { ...data } }).then(() => {
                    ElMessage.success('删除成功')
                    query()
                })
            }
        }).catch(() => { })
    }

    return {
        getDataList, sizeChangeHandle, currentChangeHandle,
        selectionChangeHandle, sortChangeHandle, deleteHandle,
        deleteBatchHandle, tabelHeight, tableHeaderDom, tableFooterDom
    }
}
